import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/routers/routers.dart';
import 'package:yt_devops/utils/func_utils.dart';

class AuthObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    var targetRoute = Routers.routers.firstWhereOrNull((element) =>
        matchRouteName(route.settings.name ?? '') ==
        matchRouteName(element.name));
    if (FuncUtils.authentication(authority: targetRoute?.auth)['pass']) {
      super.didPush(route, previousRoute);
    } else {
      Future.delayed(Duration.zero, () {
        route.navigator?.pushReplacementNamed(RouterPath.noPermission);
      });
    }
  }

  String? matchRouteName(String url) {
    var match = RegExp(r'^/(\w+)').firstMatch(url);
    return match?.group(1);
  }
}
